package com.qfmy.app.service.impl.novel;

import com.qfmy.app.mapper.novel.ReadRecordMapper;
import com.qfmy.app.service.novel.ReadRecordService;
import com.qfmy.app.vo.novel.ReadRecordVo;
import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.novel.ReadRecord;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 清风明月
 * @Package com.qfmy.app.service.impl.novel
 * @date 2025/4/14
 * @description 阅读历史
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class ReadRecordServiceImpl implements ReadRecordService {
   /**
    * 注入mapper
    */
   @Autowired
   private ReadRecordMapper readRecordMapper;
  /**
   * 注入redisTemplate
   */
   @Autowired
   private RedisTemplate<String, Object> redisTemplate;

    /**
     * @param pageNum
     * @param size
     * @return
     */
      @Override
      public List<ReadRecordVo> getRecentReadBooks(int pageNum, int size) {
         //获取当前用户id
          Integer userId = getUser();
         //计算分页
         int start = calculateStart(pageNum, size);
         //查询数据
          List<ReadRecord> re = readRecordMapper.selectRecentReadBooks(userId,start, size);
          //拷贝数据
          List<ReadRecordVo> recordVos = CopyReadRecord(re);
         return recordVos;
      }

    /**
     * 删除阅读记录
     * @param id
     */
    @Override
    public void deleteReadRecord(int id) {
        //获取用户id
        Integer userId = getUser();
        //删除阅读记录
        readRecordMapper.deleteReadRecord(userId, id);
    }

    /**
     * 清除阅读记录
     */
    @Override
    public void clearReadRecord() {
        //获取用户id
        Integer userId = getUser();
        //清除阅读记录
        readRecordMapper.clearReadRecord(userId);
    }

    /**
     * 获取最新阅读记录
     * @return
     */
    @Override
    public ReadRecordVo getNewestReadRecord() {
        //获取用户id
        Integer userId = getUser();
        //查询最新阅读记录
        ReadRecord re = readRecordMapper.selectNewestReadRecord(userId,null);
        if(re == null)
        {
             return null;
        }
        //拷贝数据
        ReadRecordVo readRecordVo = new ReadRecordVo();
        BeanUtils.copyProperties(re, readRecordVo);
        return readRecordVo;
    }

    /**
     * 保存阅读记录
     * @param bookId
     * @param chapterId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveReadRecord(int bookId, int chapterId) {
        //获取用户id
        Integer userId = getUser();
        //根据用户id和书籍id查询阅读记录
        ReadRecord readRecord = readRecordMapper.selectNewestReadRecord(userId, bookId);
        //判断是否为空
        if (readRecord == null) {
            //创建阅读记录
            ReadRecord re = new ReadRecord();
            re.setUserId(userId);
            re.setBookId(bookId);
            re.setChapterId(chapterId);
            //保存阅读记录
            readRecordMapper.insertReadRecord(re);
        }else{
            //更新阅读记录
            readRecord.setChapterId(chapterId);
            readRecordMapper.updateReadRecord(readRecord);
        }
    }

    /**
     * 根据id查询阅读记录
     * @param bookId
     * @return
     */
    @Override
    public ReadRecordVo getReadRecordByid(int bookId) {
        //获取用户id
        Integer userId = getUser();
        //查询阅读记录
        ReadRecord re = readRecordMapper.selectNewestReadRecord(userId, bookId);
        if(re == null)
        {
            return new ReadRecordVo();
        }
        //拷贝数据
        ReadRecordVo readRecordVo = new ReadRecordVo();
        BeanUtils.copyProperties(re, readRecordVo);
        return readRecordVo;
    }

    /**
     * 拷贝数据
     * @param re
     * @return
     */
    @Nullable
    @Contract(pure = true)
    private List<ReadRecordVo> CopyReadRecord(@NotNull List<ReadRecord> re) {
        //判断是否有数据
        if (re.isEmpty()) {
            return new ArrayList<>();
        }
        //创建集合
        List<ReadRecordVo> recordVos = new ArrayList<>();
        //使用流的方式拷贝数据
        re.stream().forEach(readRecord -> {
            ReadRecordVo readRecordVo = new ReadRecordVo();
            BeanUtils.copyProperties(readRecord, readRecordVo);
            recordVos.add(readRecordVo);
        });
        return recordVos;
    }


    /**
      * 获取当前用户
      *
      * @return
      */
      @Nullable
       @Contract(pure = true)
       private Integer getUser() {
       LoginUser loginUser = LoginUserHolder.getLoginUser();
       if (loginUser == null) {
          throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
       }
       //获取用户id
       Integer userId = loginUser.getUserId();
       return userId;
       }

   /**
     * 计算分页起始位置
     * @param pageNum 当前页码
     * @param size 每页大小
     * @return 起始位置
     */
    private int calculateStart(int pageNum, int size) {
     // 设置默认值
     if (pageNum <= 0) {
      pageNum = 1;
     }
     if (size <= 0) {
      size = 10;
     }
     // 计算分页起始位置
     return (pageNum - 1) * size;
    }

}
